﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain;
using Enyim.Caching;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Casamiel.Application.Commands.Wechat
{

    /// <summary>
	///  预点单支付成功小程序推送
	/// </summary>
    public sealed class PreOrderPaySucessSubscribeMessage : SubscribeMessageModel
	{

        private string page;

        /// <summary>
		/// 
		/// </summary>
		/// <param name="OpenId"></param>
        public PreOrderPaySucessSubscribeMessage(string OpenId) : base(OpenId)
		{

		}

        /// <summary>
        /// 消息模板ID
        /// </summary>
        [JsonProperty("template_id")]
        public new string TemplateId => "Qz9BThvGOcN-MYDznwBaTbejmcbI7AE9PqR7DnqEbrQ";//"264";

        /// <summary>
        /// 跳转小程序类型：developer开发版、trial体验版、formal正式版，默认为正式版
        /// </summary>
        [JsonProperty("miniprogram_state")]
        public new string MiniprogramState => "formal";


        /// <summary>
        /// 设置小程序订阅消息跳转页面
        /// </summary>
        /// <param name="pageurl"></param>

        public void SetPageUrl(string pageurl)
        {
            page = pageurl;
        }
        /// <summary>
        /// 点击模板卡片后的跳转页面
        /// </summary>
        [JsonProperty("page")]
        public new string Page {
            get {
                return page;
            }
            set {
                page = value;
                return;
            }
        }
        /// <summary>
        /// 設置審核訂閲消息數據
        /// </summary>
        /// <param name="Datas"></param>
        public void SetTemplateData(string[] Datas)
        {
            if (Datas is null) {
                throw new ArgumentNullException(nameof(Datas));
            }
            //取餐码         { { number1.DATA} }
            //门店名称     { { thing22.DATA} }
            //取餐地址     { { thing23.DATA} }
            //订单金额     { { amount12.DATA} }
            //订单状态     { { phrase10.DATA} }
            Dictionary<string, DataValue> data1 = new Dictionary<string, DataValue> {
                { "number1", new DataValue { Value = Datas[0] } },
			    { "thing22", new DataValue{ Value= Datas[1] }},
                { "thing23", new DataValue{ Value=Datas[2].Trim().Length>20? Datas[2].Trim().Substring(0,20):Datas[2]}},
                 { "amount12", new DataValue{ Value= Datas[3]}},
                { "phrase10", new DataValue{ Value= Datas[4] } }
             };
            Data = data1;
        }
         
    }

    /// <summary>
	/// 
	/// </summary>
	public sealed class PreOrderPaySucessSubscribeMessageCommandHandler : BaseCommandHandler, IRequestHandler<PreOrderPaySucessSubscribeMessageCommand, bool>
    {

        private readonly IWxService _wxService;
        private readonly IMiniAppSettingsRepository _miniAppSettingsRepository;

        private readonly IMemcachedClient _memcachedClient;
        private readonly string _ApiName;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="miniAppSettingsRepository"></param>
        /// <param name="memcachedClient"></param>
        /// <param name="wxService"></param>
        /// <param name="netICService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="settings"></param>
        public PreOrderPaySucessSubscribeMessageCommandHandler(IMiniAppSettingsRepository miniAppSettingsRepository,
        IMemcachedClient memcachedClient, IWxService wxService, INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
        {
            _miniAppSettingsRepository = miniAppSettingsRepository;

            _memcachedClient = memcachedClient;
            _wxService = wxService;

            _ApiName = settings.Value.ApiName;
        }

        public async Task<bool> Handle(PreOrderPaySucessSubscribeMessageCommand request, CancellationToken cancellationToken)
        {
			if (request is null) {
				throw new ArgumentNullException(nameof(request));
			}

			var miniappelist = await _miniAppSettingsRepository.GetAllAsync<ICasaMielSession>().ConfigureAwait(false);
            var miniappentity = miniappelist.Where(c => c.Sort == 3).SingleOrDefault();
            if (miniappentity == null) {
                throw new Exception("小程序未配置");
            }
            var _cacheKey = MemcachedPre + Constant.MINIAPPPTOKEN + miniappentity.AppId;
            string access_token = await _memcachedClient.GetValueAsync<string>(_cacheKey).ConfigureAwait(false);

            if (string.IsNullOrEmpty(access_token)) {
                string url = "cgi-bin/token?"; //grant_type=client_credential&appid=APPID&secret=APPSECRET";//https://api.weixin.qq.com/
                string param = string.Format(System.Globalization.CultureInfo.CurrentCulture, "appid={0}&secret={1}&grant_type={2}", miniappentity.AppId, miniappentity.Secret, "client_credential");
                string result = "";
                var client = HttpClientFactory.CreateClient("weixin");
                using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, url + param)) {
                    using var response = await client.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode) {
                        result = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
                    }
                }
                var wxopenInfo = JsonConvert.DeserializeObject<dynamic>(result);
                access_token = wxopenInfo.access_token;

                // long expires_in = wxopenInfo.expires_in;
                await _memcachedClient.AddAsync(_cacheKey, access_token, 7000).ConfigureAwait(false);
            }
            var openIdenity = await _wxService.GetByAppIdMobileAsync<ICasaMielSession>(miniappentity.AppId, request.Mobile).ConfigureAwait(false);
            if (openIdenity != null) {
                var url = "cgi-bin/message/subscribe/send?access_token={0}";

                var premessage = new PreOrderPaySucessSubscribeMessage(openIdenity.OpenId);
                premessage.SetTemplateData(request.Data);
                premessage.SetPageUrl($"selfService/pages/orderDetail/orderDetail?orderCode={request.OrderCode}");
                var content = JsonConvert.SerializeObject(premessage);
                Console.WriteLine(content);
                var result = await this.PostAsync(string.Format(CultureInfo.InvariantCulture, url, access_token), content, "weixin", cancellationToken).ConfigureAwait(false);
                OrderLogger.Trace($"PreOrderPaySucessSubscribeMessage:req:{miniappentity.AppId},{content},{request.Mobile},{request.Data[0]},{result}");

            }
            return true;
        }


    }
}
